package com.springboot.cloud.common.core.qcloud;

import com.alibaba.fastjson.JSONObject;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.faceid.v20180301.FaceidClient;
import com.tencentcloudapi.faceid.v20180301.models.GetLiveCodeRequest;
import com.tencentcloudapi.faceid.v20180301.models.GetLiveCodeResponse;
import com.tencentcloudapi.faceid.v20180301.models.LivenessCompareRequest;
import com.tencentcloudapi.faceid.v20180301.models.LivenessCompareResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Component
public class QcloudUtil {

    @Value("${qcloud.secretId}")
    private String secretId;

    @Value("${qcloud.secretKey}")
    private String secretKey;

    /**
     * @param imageUrl 图片地址
     * @param videoUrl 视频地址
     * @param code     校验码
     * @return 是否真人
     */
    public boolean livenessCompare(String imageUrl, String videoUrl, String code) {
        boolean result = false;
        String imageBase64 = Url2Base64(imageUrl);
        String videoBase64 = Url2Base64(videoUrl);
        LivenessCompareResponse response = analysis(imageBase64, videoBase64, code);
        if (response != null) {
            Float f = response.getSim();
            if (f != null && f > 70) {
                result = true;
            }
        }
        return result;
    }


    /**
     * 活体检测
     *
     * @param imageBase64  图片base64 格式
     * @param videoBase64  视频 base64 格式
     * @param validateData 校验数字
     */
    private LivenessCompareResponse analysis(String imageBase64, String videoBase64, String validateData) {
        LivenessCompareResponse resp = null;
        try {

            Credential cred = new Credential(secretId, secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            FaceidClient client = new FaceidClient(cred, "ap-beijing", clientProfile);
            Map map = new HashMap();
            map.put("ImageBase64", imageBase64);
            map.put("VideoBase64", videoBase64);
            map.put("ValidateData", validateData);
            System.out.print("ImageBase64 长度:" + imageBase64.length());
            System.out.print("videoBase64 长度:" + videoBase64.length());

            map.put("LivenessType", "LIP");
            String params = JSONObject.toJSONString(map);
            LivenessCompareRequest req = LivenessCompareRequest.fromJsonString(params, LivenessCompareRequest.class);
            resp = client.LivenessCompare(req);
            System.out.print("人脸核身返回结果:" + resp.getSim());
        } catch (Exception e) {
            System.out.print("人脸核身异常:" + e.getMessage());
        }
        return resp;
    }


    /**
     * 获取数字验证码
     */
    public String getLiveCode() {
        GetLiveCodeResponse resp = null;
        try {
            Credential cred = new Credential(secretId, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            FaceidClient client = new FaceidClient(cred, "ap-beijing", clientProfile);

            String params = "{}";
            GetLiveCodeRequest req = GetLiveCodeRequest.fromJsonString(params, GetLiveCodeRequest.class);

            resp = client.GetLiveCode(req);
            if (resp != null) {
                return resp.getLiveCode();
            }
        } catch (Exception e) {
        }
        return "";
    }


    /**
     * 远程读取image转换为Base64字符串
     *
     * @param fileUrl
     * @return
     */
    private static String Url2Base64(String fileUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;
        try {
            url = new URL(fileUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();

            outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return new BASE64Encoder().encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return fileUrl;
    }

    public static void main(String[] args) {
         String string = Url2Base64("http://uniquestatic.aispeak.com.cn/media/video/1598661918578sVNrfzcYkSmArCVkdyyP.mp4");
        System.out.println(string);
    }

}
